#pragma once
#include <unordered_map>
#include <memory>
#include "Common.hpp"

class Session{
public:
    Session(std::string usrname, std::string passwd, int seconds = 60) //默认cookie有效时间1分钟
        :_usrname(usrname),
        _passwd(passwd)
    {
        std::cout << "session : 1" << std::endl;
        srand((unsigned int)time(nullptr) ^ getpid());
        _out_time = time(nullptr) + seconds;
    }
    ~Session(){}

    time_t* GetOutTimeAddr(){return &_out_time;}

private:
    std::string _usrname;
    std::string _passwd;

    //还可以有别的属性：vip、active、createtime、timeout、pos(登陆地址...)
    time_t _out_time;
};


using session_ptr = std::shared_ptr<Session>;

//通过session_id查找对应的session
class SessionManager{
public:
    SessionManager(){}
    ~SessionManager(){}

    std::string AddSession(session_ptr ps){
        //添加对应的session_id   -> 随机形成(其实是有专门的库的，但是这里就直接自己写个简单一点了)
        uint32_t id = time(nullptr) * getpid() + rand();  //一般是不会有重复的，但是这里还是尽量保证不重复！
        while(_sessions.find(std::to_string(id)) != _sessions.end()){
            id = time(nullptr) * getpid() + rand();
        }
        std::string session_id = std::to_string(id);
        _sessions.emplace(session_id, ps);
        return session_id;
    }

    std::shared_ptr<Session> GetSession(std::string session_id){
        if(_sessions.find(session_id) == _sessions.end()) return nullptr;
        else return _sessions[session_id];
    }

private:
//前面是一个string的stringid
    std::unordered_map<std::string, session_ptr> _sessions;
};